// Pinia plugin: persist state to localStorage
export function persistPlugin({ store }) {
  const storageKey = `pinia_${store.$id}`

  // 初始化时从 localStorage 读取
  const fromStorage = localStorage.getItem(storageKey)
  if (fromStorage) {
    try {
      store.$patch(JSON.parse(fromStorage))
    } catch (error) {
      console.warn(`[pinia-persist] 解析 ${storageKey} 失败:`, error)
    }
  }

  // 订阅变化并持久化
  store.$subscribe((_, state) => {
    localStorage.setItem(storageKey, JSON.stringify(state))
  }, { detached: true })
} 